/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lib;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

import Core.Contants;
import android.content.Context;

/**
 * 
 * @author Minh Hung
 */
public class Core {
	public static Context context;
	public static Context context_private;
	public static final String PREFS_NAME = "MyPrefsFile";

	@SuppressWarnings("unchecked")
	private static synchronized Hashtable<String, Object> readDataStore(String name) {
		try {
			FileInputStream fis = context_private.openFileInput(name + ".txt");
			ObjectInputStream is = new ObjectInputStream(fis);
			Hashtable<String, Object> dataStore = null;
			if (is != null)
				dataStore = (Hashtable<String, Object>) is.readObject();
			is.close();
			return dataStore;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static synchronized void writeDataStore(String name,
			Hashtable<String, Object> dataStore) {
		try {
			FileOutputStream fos = context_private.openFileOutput(name + ".txt",
					Context.MODE_PRIVATE);
			ObjectOutputStream os = new ObjectOutputStream(fos);
			os.writeObject(dataStore);
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void deleteDataStore() {
//		writeDataStore(null);
	}

	public static synchronized Object readData(String name) {
		Hashtable<String, Object> dataStore = readDataStore( name);
		if (dataStore != null) {
			return dataStore.get(name);
		}

		return null;
	}

	public static synchronized void writeData(String name, Object data) {
		Hashtable<String, Object> dataStore = readDataStore(name);
		if (dataStore == null) {
			dataStore = new Hashtable<String, Object>();
		}

		if (data == null)
			for (Iterator<Entry<String, Object>> i = dataStore.entrySet()
					.iterator(); i.hasNext();) {
				Entry<String, Object> entry = i.next();

				if (name.equals(entry.getKey())) {
					i.remove();
				}
			}
		else
			dataStore.put(name, data);

		writeDataStore(name, dataStore);
	}
}
